<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2018/8/6
 * Time: 22:36
 */

namespace app\wx;


use app\wx\model\AccessToken;

class WxConfig
{
    /*测试账号*/
    public $appId = 'wx41c44abd02b498e1';
    public $appSecret = 'a9b9cf723b529e85fc97ffe3b8da3de0';
    /*择天惠*/
//    public $appId = 'wxfaf0651aaa283cf9';
//    public $appSecret = '75bfbee34aa42b1f879d9093fbdd9d92';

    /*正式账号---瑞祥 */
//    public $appId = 'wx3ea1000bc9e3533e';
//    public $appSecret = 'd37558667afa9e1b8ded0218aca36f11';


    //基础access_token
    public function getWxAccessToken()
    {
        $tokenTable = new AccessToken;
        //模型动态查询
        $result = $tokenTable::getByAid(1);
        if (!$result) {
            // 没有相应的记录//---- add------- 新增就要用模型来新增----
            $access_token = $this->getResAccessToken();
            $expire_time = time() + 7200;//120分钟后
            $saveResult = $tokenTable->save([
                'aid' => 1,
                'accessToken' => $access_token,
                'expireTime' => $expire_time
            ]);
            if ($saveResult) {
                return $access_token;
            }
        } else {
            if ($result->expireTime > time()) {
                return $result->accessToken;
            } else {
                //update access_token
                $access_token = $this->getResAccessToken();
                $expire_time = time() + 7200;//120分钟后
                //update 用结果集来跟新
                $saveResult = $result->save([
                    'aid' => 1,
                    'accessToken' => $access_token,
                    'expireTime' => $expire_time
                ]);
                if ($saveResult) {
                    return $access_token;
                }
            }
        }
    }

    protected function getResAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
        $res = json_decode($this->_request('get', $url), true);
        if (!array_key_exists('access_token', $res)) {
            return '';
        }
        $access_token = $res['access_token'];
        return $access_token;
//    $expire_time = time() + 7200;//120分钟后
//
//    $saveResult = $result->save([
//        'id' => 1,
//        'accessToken' => $access_token,
//        'expireTime' => $expire_time
//    ]);
//    if ($saveResult) {
//      return $access_token;
//    }
    }

    //发送请求方法

    /**
     * @param  string $method 'get'|'post' 请求的方式
     * @param  string $url URL
     * @param  array|json $data post请求需要发送的数据
     * @param  bool $ssl
     */
    public function _request($method = 'get', $url, $data = array(), $ssl = true)
    {
        //curl完成，先开启curl模块
        //初始化一个curl资源
        $curl = curl_init();
        //设置curl选项
        curl_setopt($curl, CURLOPT_URL, $url);//url
        //请求的代理信息
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';
        curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
        //referer头，请求来源
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);//设置超时时间
        //SSL相关
        if ($ssl) {
            //禁用后，curl将终止从服务端进行验证;
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            //检查服务器SSL证书是否存在一个公用名
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        }
        //判断请求方式post还是get
        if (strtolower($method) == 'post') {
            /**************处理post相关选项******************/
            //是否为post请求 ,处理请求数据
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        //是否处理响应头
        curl_setopt($curl, CURLOPT_HEADER, false);
        //是否返回响应结果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        //发出请求
        $response = curl_exec($curl);
        if (false === $response) {
            echo '<br>', curl_error($curl), '<br>';
            return false;
        }
        //关闭curl
        curl_close($curl);
        return $response;
    }

    //获取微信服务器IP地址
    function getWxServerIp()
    {
        $accessToken = "Y7cYto0UvJz1U-9NpN04lhQuBkO5BO7Sim6hCZ0GkZlLLfisnvXLjg6VTX_v7veESGX24zAIlu31GD5YXjQFWd5AYXkQTv5a1iGIwk9oxL4gPeWC3fCciWTp2e5ftVZvUXFcAHAHKS";
        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" . $accessToken;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        //5.关闭curl
        curl_close($ch);
        if (curl_error($ch)) {
            var_dump(curl_error($ch));
        }
        $arr = json_decode($res, true);
        echo "<pre>";
        var_dump($arr);
        echo "</pre>";
    }
}